<?php
/**
 * ProductRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-05 11:19:23
 * @modified   2023-05-05 11:19:23
 */

namespace Beike\Seller\Repositories;

use Beike\Seller\Models\Product;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class ProductRepo extends \Beike\Repositories\ProductRepo
{
    /**
     * 获取商品筛选对象
     *
     * @param array $filters
     * @param $sellerId  -不传为当前登录商户，传0代表所有商品，传非0代表指定商户商品
     * @return Builder
     * @throws Exception
     */
    public static function getBuilder(array $filters = [], $sellerId = null): Builder
    {
        $builder = parent::getBuilder($filters);
        if ($sellerId === null) {
            $sellerId = current_seller_user()->seller_id ?? 0;
        }
        if ($sellerId) {
            $builder->where('seller_id', $sellerId);
        }

        return $builder;
    }

    /**
     * @param $name
     * @return array
     */
    public static function autocomplete($name): array
    {
        $products = Product::query()->with('description')
            ->whereHas('description', function ($query) use ($name) {
                $query->where('name', 'like', "%$name%");
            })
            ->where('seller_id', current_seller_user()->seller_id)
            ->limit(10)->get();
        $results = [];
        foreach ($products as $product) {
            $results[] = [
                'id'     => $product->id,
                'name'   => $product->description->name,
                'status' => $product->active,
                'image'  => $product->image,
            ];
        }

        return $results;
    }

    /**
     * @return int
     * @throws Exception
     */
    public static function count(): int
    {
        return self::getBuilder()->count();
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function find($id): Model|Collection|Builder|array|null
    {
        return Product::query()->find($id);
    }

    /**
     * @param $productId
     * @param $value
     * @param $comment
     * @return void
     */
    public static function updateApprovedStatus($productId, $value, $comment): void
    {
        \Beike\Models\Product::query()->where('id', $productId)->update(['approved_status' => $value, 'approved_comment' => $comment, 'approved_at' => now()]);
    }

    /**
     * @param $ids
     * @return array
     */
    public static function getNeedApproveByIds($ids): array
    {
        $items = \Beike\Models\Product::query()->whereIn('id', $ids)->select(['id', 'seller_id', 'approved_at', 'approved_status'])->get();

        $result = [];
        foreach ($items as $item) {
            $result[$item->id] = $item->seller_id && ! $item->approved_at;
        }

        return $result;
    }

    /**
     * @param $ids
     * @param $status
     * @return void
     */
    public static function updateStatusByIds($ids, $status): void
    {
        Product::query()->whereIn('id', $ids)->whereNotNull('approved_at')->where('approved_status', true)->update(['active' => $status]);
    }

    /**
     * 通过单个或多个商品分类获取商品列表
     *
     * @param $categoryId
     * @param $filterData
     * @return LengthAwarePaginator
     */
    public static function getProductsBySellerCategory($categoryId, $filterData)
    {
        $builder = static::getBuilder(array_merge(['active' => 1], $filterData), 0)
            ->leftJoin('product_seller_categories as seller_psc', 'seller_psc.product_id', 'products.id')
            ->where('seller_psc.seller_category_id', $categoryId)
            ->reorder('products.position_seller');

        return $builder->with('inCurrentWishlist')
            ->paginate($filterData['per_page'] ?? perPage())
            ->withQueryString();
    }

    public static function disableProductsBySellerId($sellerId)
    {
        return Product::query()->where('seller_id', $sellerId)->update(['active' => 0]);
    }
}
